﻿#region
using System;
using System.Collections.Generic;
using System.Windows.Forms;

#endregion

namespace AfricaDownloader
{
    public partial class DownloadViewer : UserControl
    {
        public DownloadViewer()
        {
            InitializeComponent();
        }

        private readonly List<DownloadControl> _controls = new List<DownloadControl>();

        private int _index;

        public void AddControls(string[] urls)
        {
            ClearControls();

            List<DownloadControl> reversedControls = new List<DownloadControl>();

            for (int i = urls.Length - 1; i >= 0; i--)
            {
                var control = AddControl(urls[i]);
                reversedControls.Add(control);
            }

            reversedControls.Reverse();
            _controls.AddRange(reversedControls);

            _controls[_index].Download();
        }

        private DownloadControl AddControl(string url)
        {
            DownloadControl control = new DownloadControl();
            control.Height = 30;
            control.Dock = DockStyle.Top;
            control.SendToBack();
            control.Prepare(url);
            control.Downloaded += DownloadControl_Downloaded;

            pnlPanel.Controls.Add(control);

            return control;
        }

        private void DownloadControl_Downloaded(object sender, DownloadControl.DownloadedEventArgs e)
        {
            if (_index == _controls.Count - 1)
            {
                OnAllDownloadsCompleted(null);
            }
            else
            {
                _index++;
                _controls[_index].Download();
            }
        }

        private void ClearControls()
        {
            _index = 0;
            _controls.Clear();
            pnlPanel.Controls.Clear();
        }

        #region AllDownloadsCompleted event things for C# 3.0
        public event EventHandler<AllDownloadsCompletedEventArgs> AllDownloadsCompleted;

        protected virtual void OnAllDownloadsCompleted(AllDownloadsCompletedEventArgs e)
        {
            if (AllDownloadsCompleted != null)
                AllDownloadsCompleted(this, e);
        }

        private AllDownloadsCompletedEventArgs OnAllDownloadsCompleted(object dummy)
        {
            AllDownloadsCompletedEventArgs args = new AllDownloadsCompletedEventArgs(dummy);
            OnAllDownloadsCompleted(args);

            return args;
        }

        public class AllDownloadsCompletedEventArgs : EventArgs
        {
            public object Dummy { get; set; }

            public AllDownloadsCompletedEventArgs()
            {
            }

            public AllDownloadsCompletedEventArgs(object dummy)
            {
                Dummy = dummy;
            }
        }
        #endregion
    }
}